import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { SystemExpBuilder } from 'utils/SystemExpUtil'
import { ElMessage } from 'element-plus'

export interface AjaxReqConfigType extends AxiosRequestConfig {
  /**
   * 当出现异常时, 是否使用统一的异常提示. 默认:true
   */
  whenExpShowErrorTips?: boolean
}

export interface ApiRespType {
  code: number
  data: any
  msg: string
}

const axiosInstance = axios.create()
axiosInstance.interceptors.response.use(
  axiosResp => {
    const { whenExpShowErrorTips = true } =
      axiosResp.config as AjaxReqConfigType
    const apiResp = axiosResp.data as ApiRespType
    if (!apiResp) {
      console.log('后端接口请求成功，但接口未响应任何数据')
      return
    }
    const { msg = '后端服务异常' } = apiResp
    switch (apiResp.code) {
      case 200: {
        // 后端处理成功
        return apiResp.data
      }
      default: {
        // 其他所有业务状态码，都认为是后端处理异常
        if (whenExpShowErrorTips) {
          ElMessage.error(msg)
        }
        throw SystemExpBuilder.buildCommApiExp(apiResp.code, apiResp.msg)
      }
    }
  },
  (error: any) => {
    // TODO 这里处理非200的http状态码响应
    console.log('axios response onReject:', error)
  }
)
export const AjaxUtil = {
  getReq<T = any, R = AxiosResponse<T>>(
    url: string,
    reqData: unknown = {}
  ): Promise<R> {
    return axiosInstance.get<T, R>(url, { params: reqData })
  },
  postReq<T = any, R = AxiosResponse<T>>(
    url: string,
    reqData: unknown = {}
  ): Promise<R> {
    return axiosInstance.post(url, reqData)
  },
}
